package com.starxg.m3u8.controller;

import com.starxg.m3u8.download.M3U8AnalysisCallback;
import com.starxg.m3u8.download.M3U8DownloadCallback;
import com.starxg.m3u8.download.M3U8Merger;
import com.starxg.m3u8.gui.DialogUtils;
import com.starxg.m3u8.gui.LoadingDialog;
import com.starxg.m3u8.parser.M3U8;
import com.starxg.m3u8.parser.M3U8Item;
import com.starxg.m3u8.parser.M3U8Parser;
import com.starxg.m3u8.parser.M3U8Text;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Window;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import com.starxg.m3u8.download.M3U8Analysis;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@Slf4j
public class MergerController extends BaseController {
    @FXML
    private Button btnSaveFilePath;
    @FXML
    private Button btnM3U8Path;
    @FXML
    private TextField txtSaveFilePath;
    @FXML
    private TextField txtKey;
    @FXML
    private TextField txtM3U8Path;
    @FXML
    private Button btnMerger;

    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {
        btnMerger.setOnAction(e -> {
            if (StringUtils.isBlank(txtM3U8Path.getText())) {
                alert("请选择 M3U8 地址");
            } else if (StringUtils.isBlank(txtSaveFilePath.getText())) {
                alert("请选择合并文件后的位置");
            } else {

                File file = new File(txtM3U8Path.getText());
                if (!file.exists()) {
                    alert("M3U8文件不存在", Alert.AlertType.ERROR);
                    return;
                }

                try (var is = new FileInputStream(file)) {
                    String text = IOUtils.toString(is, StandardCharsets.UTF_8);
                    M3U8Text m3u8Text = M3U8Parser.m3u8Text(new URL("https://www.soluow.com/"), text, true);
                    merge(m3u8Text);
                } catch (Exception ex) {
                    log.error(ex.getMessage(), ex);
                    alert(ex.getMessage(), Alert.AlertType.ERROR);
                }
            }
        });

        btnM3U8Path.setOnAction(e -> {
            File file = DialogUtils.showOpenFileDialog("请选择保存的文件", null, getStage(), null);
            if (file != null) {
                txtM3U8Path.setText(file.getAbsolutePath());
            }
        });

        btnSaveFilePath.setOnAction(e -> {
            File file = DialogUtils.showSaveFileDialog("请选择保存的文件", null, getStage(), null);
            if (file != null) {
                txtSaveFilePath.setText(file.getAbsolutePath());
            }
        });
    }

    private void analysis(URL url) {
        M3U8Analysis analysis = new M3U8Analysis(url);
        analysis.start(new M3U8AnalysisCallback() {
            private LoadingDialog dialog;

            @Override
            public void before() {
                dialog = new LoadingDialog("解析中");
                dialog.initOwner(getStage());
                dialog.show();
            }

            @Override
            public void failed(Throwable e) {
                log.error("解析失败。原因:{}", e.getMessage(), e);
                alert("解析失败。原因:" + e.getMessage(), Alert.AlertType.ERROR);
            }

            @Override
            public void succeeded(M3U8 m3u8) {
                if (m3u8 instanceof M3U8Text) {
                    merge((M3U8Text) m3u8);
                } else {
                    alert("暂不支持其他M3U8格式的合并。例如：直播流");
                }
            }

            @Override
            public void completed() {
                dialog.closeNow();
            }
        });
    }

    private void merge(M3U8Text m3u8Text) {
        File file = new File(txtSaveFilePath.getText());
        new M3U8Merger(null,m3u8Text.getItems(), file).start(new M3U8DownloadCallback<>() {
            private LoadingDialog dialog;

            @Override
            public void before(M3U8Merger before) {
                dialog = new LoadingDialog("合并中");
                dialog.initOwner(getStage());
                dialog.show();
            }

            @Override
            public void part(M3U8Item item, Throwable e) {
                log.error("分片 [{}] 合并失败。原因:{}", item.getName(), e.getMessage(), e);
            }

            @Override
            public void failed(Throwable e) {
            }

            @Override
            public void part(M3U8Item item) {
                log.error("分片 [{}] 合并成功", item.getName());
            }

            @Override
            public void completed() {
                Platform.runLater(() -> {
                    dialog.closeNow();
                    if (confirm("合并分片完成，是否打开合并后的文件目录？")) {
                        openFinderLightFile(file);
                    }
                });
            }

        });

    }

    @Override
    public Window getStage() {
        return btnM3U8Path.getScene().getWindow();
    }
}
